/**
 * An apex class that creates a portal user
 */
 
public with sharing class SiteRegisterController {

    // PORTAL_ACCOUNT_ID is the account on which the contact will be created on and then enabled as a portal user.       
    private static Id PORTAL_ACCOUNT_ID = '001U0000005f7UQ';
    
    public SiteRegisterController () {
    }

/*********************Declare variables************************************************************************/
 
    public String username {get; set;}
    public String email {get; set;}
    public String password {get; set {password = value == null ? value : value.trim(); } }
    public String confirmPassword {get; set { confirmPassword = value == null ? value : value.trim(); } }
    public String firstName {get; set { firstName = value == null ? value : value.trim(); } }
    public String lastName {get; set { lastName = value == null ? value : value.trim(); } }
    public String utorId {get; set { utorId = value == null ? value : value.trim(); } }
    public Long studentNumber {get; set;}
    
    // checkbox for Tutor role
    public String[] roles = new String[]{};
    
    public List<SelectOption> getItems() {
        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption('Tutor', 'Yes'));
        return options;
   }
   
   public String[] getRoles() {
        return roles;
    }

    public void setRoles(String[] Roles) {
        this.roles = roles;
    }
    
/*********************Helper methods***************************************************************************/
    
    // check invalid fields
    private boolean isValidUTORid(){
        return !(utorId == null);
    }
    
    private boolean isValidFirstName(){
        return (firstName != null) && (firstName.length() < 30);
    }
    
    private boolean isValidLastName(){
        return (lastName != null) && (lastName.length() < 30);
    }    
            
    private boolean isValidPassword() {
        return password == confirmPassword;
    }
    
    private boolean isValidStudentNum() {
        return (studentNumber > 0) && (studentNumber < 1000000000);
    }
        
    private boolean isValidEmail() {
        return email.endsWith('@utsc.utoronto.ca') || email.endswith('@utoronto.ca') || email.endswith('@utm.utoronto.ca');
    }
    
    // send welcome email to new user
    public void sendEmail(User u) {
        Messaging.reserveSingleEmailCapacity(2);
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {u.Email};
        mail.setToAddresses(toAddresses);
        mail.setSenderDisplayName('TutorMe');
        mail.setSubject('Welcome to TutorMe');
        mail.setHtmlBody('Hi ' + u.firstname + ' ' + u.lastname + ',<br/><br/>'
        + 'Thank you for choosing TutorMe, a web-based tutor system for UT students.<br/><br/>'
        + 'Your user name is <b>' + u.UTORid__c + '</b>.<br/>'
        + 'Please go to My Profile page and update your profile after login.<br/>'
        + 'If you have applied for Tutor, please wait for the Admin to approve your application.<br/><br>'
        + 'Contact the Admin if you have any concerns or encounter any bugs.<br/><br/>'
        + 'Thanks,<br/>TutorMe Admin');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
    }
 
/**********************Set up User Object**********************************************************************/
   
    public PageReference registerUser() {
        
        if (!isValidUTORid()){
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.Error, 'UTORid cannot be null.');
            ApexPages.addMessage(msg);
            return null;
        }
        
        if (!isValidFirstName()){
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.Error, 'First Name must be less than 30 characters and not null.');
            ApexPages.addMessage(msg);
            return null;
        }      
        
        if (!isValidLastName()){
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.Error, 'Last Name must be less than 30 characters and not null.');
            ApexPages.addMessage(msg);
            return null;
        }    
        
        if (!isValidStudentNum()){
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.Error, 'Student Number must be nine digits.');
            ApexPages.addMessage(msg);
            return null;
        }
        
        // only valid utoronto e-mails are acceptable
        if (!isValidEmail()) {
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.Error, 'Invalid email, must be utoronto, utsc or utm email.');
            ApexPages.addMessage(msg);
            return null;
        }
        
        // password may be null, in that case a random password will be sent to the user
        if (!isValidPassword()) {
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.Error, Label.site.passwords_dont_match);
            ApexPages.addMessage(msg);
            return null;
        }
        
        // set User fields
        User u = new User();
        u.username = utorId;
        u.Email = email;
        u.CommunityNickname = utorId;
        u.FirstName = firstName;
        u.LastName = lastName;
        u.UTORid__c = utorId;
        u.Student_Number__c = String.valueof(studentNumber);
        sendEmail(u);

        // send an email if the user checks Tutor box
        if (roles.size() == 1) {
            Tutor_Application__c a = new Tutor_Application__c(Name=u.utorId__c);
            insert a;
            u.Last_Sent__c = datetime.Now();
            MyProfilePageController.sendEmail(u);
        }

/*********************Registration method**********************************************************************/

        String accountId = PORTAL_ACCOUNT_ID;

        String userId = Site.createPortalUser(u, accountId, password);
        if (userId != null) { 
            if (password != null && password.length() > 1) {                
                return Site.login(utorId, password, null);
            }
            else {
                PageReference page = System.Page.SiteRegisterConfirm;
                page.setRedirect(true);
                return page;
            }
        }
        return null;
    }

/*********************Test method******************************************************************************/
    
    // test invalid email
    static testMethod void test2() {
        SiteRegisterController controller = new SiteRegisterController();
        controller.utorId = 'test';
        controller.firstName = 'test';
        controller.lastName = 'test';
        controller.studentNumber = 999111999;
        controller.email = 'test@gmail.com';
        System.assert(controller.registerUser() == null);
        controller.password = 'abcd1234';
        controller.confirmPassword = 'abcd1234';
        System.assert(controller.registerUser() == null);
    }
}